package cn.changeforyou.web.dao.mybatis.ext.config;

import cn.hutool.core.util.ReflectUtil;
import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;

/**
 * @author zhyu
 * @version 1.0
 * @date 2022/2/26 22:21
 */

public class MybatisExtInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {


    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName)
            throws BeansException {
        if (beanName.endsWith("MybatisAutoConfiguration")) {
            MybatisAutoConfiguration mybatisAutoConfiguration = (MybatisAutoConfiguration) bean;
            Object properties = ReflectUtil.getFieldValue(mybatisAutoConfiguration, "properties");
            MybatisProperties mybatisProperties = (MybatisProperties) properties;
            Configuration configuration = mybatisProperties.getConfiguration();
            if (null == configuration) {
                configuration = new Configuration();
                configuration.setMapUnderscoreToCamelCase(true);
                mybatisProperties.setConfiguration(configuration);
            }
        }
        return null;
    }

}
